package com.zklh.leetcode.tree.middle.problem116;

import com.zklh.leetcode.tree.model.Node;

import java.util.LinkedList;
import java.util.Queue;

/**
 *
 * @author 坐看落花
 * @version 1.0
 * @date 2021/1/10 19:27
 */
public class Solution {



    public Node connect(Node root) {
        if (root == null || root.left == null) {
            return root;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        Node lastNode;
        Node cur;
        int num = 0;
        while (!queue.isEmpty()) {
            lastNode = null;
            int len = queue.size();
            for (int i = 0; i < len; i++) {
                cur = queue.remove();
                if (lastNode != null) {
                    lastNode.next = cur.left;
                }
                cur.left.next = cur.right;
                lastNode = cur.right;
                if (cur.left.left != null) {
                    queue.add(cur.left);
                    queue.add(cur.right);
                }
                System.out.println(++num);
            }

        }
        return root;
    }

    private void levelTraversalAndConnect(Queue<Node> queue) {

    }


    public static void main(String[] args) {
        Solution solution = new Solution();
        Node  a = new Node(1);
        Node  b = new Node(2);
        Node  c = new Node(3);
        Node  d = new Node(4);
        Node  e = new Node(5);
        Node  f = new Node(6);
        Node  g = new Node(7);
        a.left = b;
        a.right = c;
        b.left = d;
        b.right = e;
        c.left = f;
        c.right =g;
        Node temp = solution.connect(a);
        while (temp != null) {
            System.out.println(temp.val);
            temp = temp.next;
        }
    }

}
